//
//  jingtai.m
//  Unity-iPhone
//
//  Created by 刘艺 on 13-9-3.
//
//
#include <CommonCrypto/CommonDigest.h>
#import "jingtai.h"
#define FileHashDefaultChunkSizeForReadingData 1024*8
@implementation jingtai
+ (jingtai *)sharedSingleton
{
    static jingtai *sharedSingleton=nil;//之前忘记赋值为nil,程序一直出错
    
    @synchronized(self)
    {
        if (!sharedSingleton)
        {
            sharedSingleton = [[jingtai alloc] init];
            sharedSingleton.Downloadqueue = [[NSMutableArray alloc] init];
            sharedSingleton.URLappList =[[NSMutableArray alloc]init];
        }
        return sharedSingleton;
    }
}
CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath,size_t chunkSizeForReadingData) {
    
    // Declare needed variables
    
    CFStringRef result = NULL;
    
    CFReadStreamRef readStream = NULL;
    
    // Get the file URL
    
    CFURLRef fileURL =
    
    CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                  
                                  (CFStringRef)filePath,
                                  
                                  kCFURLPOSIXPathStyle,
                                  
                                  (Boolean)false);
    
    if (!fileURL) goto done;
    
    // Create and open the read stream
    
    readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
                                            
                                            (CFURLRef)fileURL);
    
    if (!readStream) goto done;
    
    bool didSucceed = (bool)CFReadStreamOpen(readStream);
    
    if (!didSucceed) goto done;
    
    // Initialize the hash object
    
    CC_MD5_CTX hashObject;
    
    CC_MD5_Init(&hashObject);
    
    // Make sure chunkSizeForReadingData is valid
    
    if (!chunkSizeForReadingData) {
        
        chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData;
        
    }
    
    // Feed the data to the hash object
    
    bool hasMoreData = true;
    
    while (hasMoreData) {
        
        uint8_t buffer[chunkSizeForReadingData];
        
        CFIndex readBytesCount = CFReadStreamRead(readStream,(UInt8 *)buffer,(CFIndex)sizeof(buffer));
        
        if (readBytesCount == -1) break;
        
        if (readBytesCount == 0) {
            
            hasMoreData = false;
            
            continue;
            
        }
        
        CC_MD5_Update(&hashObject,(const void *)buffer,(CC_LONG)readBytesCount);
        
    }
    
    // Check if the read operation succeeded
    
    didSucceed = !hasMoreData;
    
    // Compute the hash digest
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5_Final(digest, &hashObject);
    
    // Abort if the read operation failed
    
    if (!didSucceed) goto done;
    
    // Compute the string result
    
    char hash[2 * sizeof(digest) + 1];
    
    for (size_t i = 0; i < sizeof(digest); ++i) {
        
        snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
        
    }
    
    result = CFStringCreateWithCString(kCFAllocatorDefault,(const char *)hash,kCFStringEncodingUTF8);
    
    
    
done:
    
    if (readStream) {
        
        CFReadStreamClose(readStream);
        
        CFRelease(readStream);
        
    }
    
    if (fileURL) {
        
        CFRelease(fileURL);
        
    }
    
    return result;
    
}
+(NSString*)getFileMD5WithPath:(NSString*)path

{
    
    return (__bridge_transfer NSString *)FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
    
}
+(NSString *) getlocalshopversion
{
    NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString *docpath = [docpaths objectAtIndex:0];
    NSString * versionpath=[NSString stringWithFormat:@"%@/IconVersion.plist",docpath];
    if([fm fileExistsAtPath:versionpath])
    {
        NSDictionary * dic = [[NSDictionary alloc] initWithContentsOfFile:versionpath];
        return [dic objectForKey:@"Shopversion"];
    }
    else
    {
        return @"0";
    }
}
+(NSString *) getlocalkindversion
{
    NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString *docpath = [docpaths objectAtIndex:0];
    NSString * versionpath=[NSString stringWithFormat:@"%@/IconVersion.plist",docpath];
    if([fm fileExistsAtPath:versionpath])
    {
        NSDictionary * dic = [[NSDictionary alloc] initWithContentsOfFile:versionpath];
        return [dic objectForKey:@"Kindversion"];
    }
    else
    {
        return @"0";
    }
}
+(NSString *) getlocalcontentversion
{
    NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString *docpath = [docpaths objectAtIndex:0];
    NSString * versionpath=[NSString stringWithFormat:@"%@/IconVersion.plist",docpath];
    if([fm fileExistsAtPath:versionpath])
    {
        NSDictionary * dic = [[NSDictionary alloc] initWithContentsOfFile:versionpath];
        return [dic objectForKey:@"Contentversion"];
    }
    else
    {
        return @"0";
    }
}
+(void)setlocalcontentVersion : (NSString * )version
{
    NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString *docpath = [docpaths objectAtIndex:0];
    NSString * versionpath=[NSString stringWithFormat:@"%@/IconVersion.plist",docpath];
    if([fm fileExistsAtPath:versionpath])
    {
        NSMutableDictionary * dic = [[NSMutableDictionary alloc] initWithContentsOfFile:versionpath];
        [dic setValue:version forKey:@"Contentversion"];
        [dic writeToFile:versionpath atomically:YES];
    }
    else
    {
        NSDictionary * dic = [NSDictionary dictionaryWithObjects:@[@"0",@"0",@"0"] forKeys:@[@"Shopversion",@"Kindversion",@"Contentversion"]];
        
        [dic writeToFile:versionpath atomically:YES];
        
    }

}
+(void)setlocalshopVersion : (NSString * )version
{
    NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString *docpath = [docpaths objectAtIndex:0];
    NSString * versionpath=[NSString stringWithFormat:@"%@/IconVersion.plist",docpath];
    if([fm fileExistsAtPath:versionpath])
    {
        NSMutableDictionary * dic = [[NSMutableDictionary alloc] initWithContentsOfFile:versionpath];
        [dic setValue:version forKey:@"Shopversion"];
         [dic writeToFile:versionpath atomically:YES];
    }
    else
    {
        NSDictionary * dic = [NSDictionary dictionaryWithObjects:@[@"0",@"0",@"0"] forKeys:@[@"Shopversion",@"Kindversion",@"Contentversion"]];
        
        [dic writeToFile:versionpath atomically:YES];

    }

}
+(void)setlocalkindVersion : (NSString * )version
{
    NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString *docpath = [docpaths objectAtIndex:0];
    NSString * versionpath=[NSString stringWithFormat:@"%@/IconVersion.plist",docpath];
    if([fm fileExistsAtPath:versionpath])
    {
        NSMutableDictionary * dic = [[NSMutableDictionary alloc] initWithContentsOfFile:versionpath];
        [dic setValue:version forKey:@"Kindversion"];
         [dic writeToFile:versionpath atomically:YES];
    }
    else
    {
        NSDictionary * dic = [NSDictionary dictionaryWithObjects:@[@"0",@"0",@"0"] forKeys:@[@"Shopversion",@"Kindversion",@"Contentversion"]];
        
        [dic writeToFile:versionpath atomically:YES];
    }
    
}
+(UIImage *) getImageFromURL:(NSString *)fileURL  andislocal:(BOOL) islocal andismustdonwload:(BOOL)isMustdownload{
    
   // NSLog(@"执行图片下载函数");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString * Icoonpath=[NSString stringWithFormat:@"%@/Icon/%@",path,[fileURL lastPathComponent]];
    NSString * iconp =[NSString stringWithFormat:@"%@/Icon",path];
    NSFileManager * fm = [NSFileManager defaultManager];
    BOOL isdir=FALSE;
    BOOL isexit = [fm fileExistsAtPath:iconp isDirectory:&isdir];
    if(!(isexit && isdir))
    {
        [fm createDirectoryAtPath:iconp withIntermediateDirectories:YES attributes:nil error:nil];
    }
    UIImage * result;
    NSData * data;
    NSFileManager * filemanager = [NSFileManager defaultManager];
    if(!islocal)
    {
        if(isMustdownload)
        {
            NSLog(@"isdownload");
            data =[NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
        }
        else{
            
        
            if([filemanager fileExistsAtPath:Icoonpath])
            {
            
                data=[NSData dataWithContentsOfFile:Icoonpath];
            }
            else
            {
                data= [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
                if(data == nil)
                {
                    NSLog(@"图片不能加载！");
                }
            }
        }
         result = [UIImage imageWithData:data];
        [data writeToFile:Icoonpath atomically:YES];
    }
    else
    {
         data=[NSData dataWithContentsOfFile:fileURL];
         result = [UIImage imageWithData:data];
    }
   
    
    return result;
    
}

+(id)getviewcontrollerfromstoryboard:(NSString *)nameid
{
    UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  return  [storyboard instantiateViewControllerWithIdentifier:nameid];
}
@end